package code.homework;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cc
 * @create 2023-01-28  22:08
 */
public class Insert {

    /**
     * [[0,2],[4,6],[7,9]]   [1,3]
     *
     *
     */

    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> resultList = new ArrayList<>();
        int left = newInterval[0];
        int right = newInterval[1];
        // 合并后的数组（也有可能是原数组）
        int[] merge = {newInterval[0],newInterval[1]};
        boolean needAdd = true;
        for(int[] arr:intervals){
            if(arr[1] < left ){
                resultList.add(arr);
            }
            if(arr[0] > right){
                if(needAdd){
                    resultList.add(merge);
                    needAdd = false;
                }
                resultList.add(arr);
            }
            //包含
            if(arr[0] <=left && arr[1] >= left){
                merge[0] = Math.min(merge[0],arr[0]);
            }
            if(arr[0] <= right && arr[1] >= right){
                merge[1] = Math.max(merge[1],arr[1]);
                if(needAdd){
                    resultList.add(merge);
                    needAdd = false;
                }
            }
        }
        if(needAdd){
            resultList.add(merge);
        }
        int[][] res = new int[resultList.size()][2];
        for (int i = 0; i < resultList.size(); ++i) {
            res[i] = resultList.get(i);
        }
        return res;

    }


}
